package com.liukai.todo_android.ui.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.PopupMenu;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.appcompat.widget.AppCompatButton;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.liukai.todo_android.R;
import com.liukai.todo_android.call_back.IDeleteScheduleCallBack;
import com.liukai.todo_android.call_back.IUpdateScheduleCallBack;
import com.liukai.todo_android.common.utils.Constants;
import com.liukai.todo_android.common.utils.JSONUtil;
import com.liukai.todo_android.common.utils.LogUtils;
import com.liukai.todo_android.entity.ItemVo;
import com.liukai.todo_android.presenter.DeleteSchedulePresenter;
import com.liukai.todo_android.presenter.UpdateSchedulePresenter;
import com.liukai.todo_android.ui.activity.ConcentrationActivity;
import com.liukai.todo_android.ui.adapter.ToDoRecyclerViewAdapter;
import com.liukai.todo_android.common.base.BaseFragment;
import com.liukai.todo_android.call_back.IFindTodoCallBack;
import com.liukai.todo_android.entity.Resp;
import com.liukai.todo_android.presenter.FindSchedulePresenter;
import com.liukai.todo_android.common.utils.State;
import com.liukai.todo_android.ui.dialog.AddOrUpdateScheduleDialog;
import com.liukai.todo_android.ui.dialog.ItemDetailDialog;

import java.util.List;

import butterknife.BindView;

/**
 * @author ：liukai
 * @date ：Created in 2021/8/9 4:16 下午
 * @description：我的信息页面
 * @modified By：
 * @version: $
 */
public class TodoFragment extends BaseFragment implements IFindTodoCallBack, IUpdateScheduleCallBack, IDeleteScheduleCallBack {

    @BindView(R.id.btn_add)
    FloatingActionButton btnAdd;
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.et_search)
    EditText etSearch;
    @BindView(R.id.btn_empty)
    AppCompatButton btnEmpty;

    private Context context;
    private ToDoRecyclerViewAdapter toDoRecyclerViewAdapter;
    private View view;
    private AddOrUpdateScheduleDialog addScheduleDialog;
    private FindSchedulePresenter findSchedulePresenter;
    private UpdateSchedulePresenter updateSchedulePresenter;
    private AddOrUpdateScheduleDialog updateScheduleDialog;
    private boolean isSearch = false;

    @Override
    protected void initDate(View view) {
        setUpState(State.LOADING);
        findSchedulePresenter = new FindSchedulePresenter();
        findSchedulePresenter.registerCallback(this);
        updateSchedulePresenter = new UpdateSchedulePresenter();
        updateSchedulePresenter.registerCallback(this);
    }

    @Override
    protected Context getFragmentContext(View view) {
        context = view.getContext();
        this.view = view;
        reLoadScheduleList();
        return null;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_todo;
    }

    @Override
    protected void initView(View view) {
        super.initView(view);
    }

    @Override
    protected void initAdapter(View view) {
        toDoRecyclerViewAdapter = new ToDoRecyclerViewAdapter(context);
        LinearLayoutManager layoutManager = new LinearLayoutManager(context);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(toDoRecyclerViewAdapter);
    }

    @Override
    protected void initListener() {
        /**
         * 新增按钮的点击事件
         */
        btnAdd.setOnClickListener(v -> {
            addScheduleDialog = new AddOrUpdateScheduleDialog(context,
                    AddOrUpdateScheduleDialog.MODEL_ADD);
            initAddCallBack();
        });

        /**
         * 列表item按钮的点击事件
         */
        toDoRecyclerViewAdapter.setOnItemClick(new ToDoRecyclerViewAdapter.OnItemClick() {
            /**
             * 更多按钮
             * @param view
             * @param itemVo
             */
            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void moreClick(View view, ItemVo itemVo) {
                PopupMenu popupMenu = showPopupMenu(view);
                // 设置更多菜单选项的点击事件
                setMenuItemListener(popupMenu, itemVo);
            }

            /**
             * 专注按钮
             * @param itemVo
             */
            @Override
            public void concentrationClick(ItemVo itemVo) {
                Toast.makeText(context, "专注", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(context, ConcentrationActivity.class);
                intent.putExtra(Constants.ITEM_VO_KEY, itemVo);
                startActivity(intent);
            }

            @Override
            public void itemClick(ItemVo itemVo) {
                ItemDetailDialog itemDetailDialog = new ItemDetailDialog(context, itemVo);
                itemDetailDialog.show();
            }
        });

        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                findSchedulePresenter.searchNotFinishedSchedule(Constants.getUserId(context),
                        etSearch.getText().toString());
                isSearch = true;
            }
        });

        btnEmpty.setOnClickListener(v -> {
            etSearch.setText("");
        });


    }

    /**
     * 新增成功后的回调方法
     */
    private void initAddCallBack() {
        addScheduleDialog.setOnSuccessListener(() -> {
            reLoadScheduleList();
        });
    }

    /**
     * 重新获取待办事项的数据列表
     */
    private void reLoadScheduleList() {
        findSchedulePresenter.findNotFinishedScheduleByUserId(Constants.getUserId(context));
    }

    /**
     * 修改成功后的回调方法
     */
    private void initUpdateCallBack() {
        updateScheduleDialog.setOnUpdateSuccessListener(() -> {
            reLoadScheduleList();
        });
    }

    /**
     * 更多菜单的点击事件
     *
     * @param popupMenu
     * @param itemVo
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    private void setMenuItemListener(PopupMenu popupMenu, ItemVo itemVo) {
        popupMenu.setOnMenuItemClickListener(item -> {
            int itemId = item.getItemId();
            switch (itemId) {
                case R.id.edit:
                    Toast.makeText(context, "编辑", Toast.LENGTH_SHORT).show();
                    updateSchedule(itemVo);
                    break;
                case R.id.delete:
                    Toast.makeText(context, "删除", Toast.LENGTH_SHORT).show();
                    delete(itemVo);
                    break;
                case R.id.setDone:
                    Toast.makeText(context, "设为已完成", Toast.LENGTH_SHORT).show();
                    updateSchedulePresenter.setScheduleFinish(itemVo);
                    break;
                default:
            }
            return true;
        });
    }

    /**
     * 编辑待办
     *
     * @param itemVo
     */
    private void updateSchedule(ItemVo itemVo) {
        updateScheduleDialog = new AddOrUpdateScheduleDialog(context,
                AddOrUpdateScheduleDialog.MODEL_UPDATE, itemVo);
        initUpdateCallBack();
    }

    /**
     * 删除待办
     *
     * @param itemVo
     */
    private void delete(ItemVo itemVo) {
        DeleteSchedulePresenter deleteSchedulePresenter = new DeleteSchedulePresenter();
        deleteSchedulePresenter.registerCallback(this);
        deleteSchedulePresenter.deleteSchedule(itemVo.getId());
    }

    /**
     * 显示弹出菜单
     *
     * @param view
     */
    private PopupMenu showPopupMenu(View view) {
        PopupMenu popupMenu = new PopupMenu(context, view);
        popupMenu.getMenuInflater().inflate(R.menu.todo_more_menu, popupMenu.getMenu());
        popupMenu.show();
        return popupMenu;
    }

    @Override
    protected void release() {
        super.release();
    }

    /**
     * 查找待办成功
     *
     * @param resp
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void findScheduleSuccess(Resp resp) {
        LogUtils.e(getClass(), resp.toString());
        List<ItemVo> itemVos = JSONUtil.resolverResultList(resp, ItemVo.class);
        itemVos.forEach(System.out::println);

        // 判断是搜索功能还是获取所有
        if (isSearch && !"".equals(etSearch.getText().toString())) {
            toDoRecyclerViewAdapter.setScheduleList(itemVos,
                    ToDoRecyclerViewAdapter.STYLE_SEARCH, etSearch.getText().toString());
        } else {
            toDoRecyclerViewAdapter.setScheduleList(itemVos,
                    ToDoRecyclerViewAdapter.STYLE_FIND_ALL, etSearch.getText().toString());
        }
        setUpState(State.SUCCESS);
        isSearch = false;
    }

    /**
     * 查找待办失败
     *
     * @param resp
     */
    @Override
    public void findScheduleError(Resp resp) {
        LogUtils.e(getClass(), resp.toString());
        setUpState(State.ERROR);
        isSearch = false;
    }

    /**
     * 修改待办成功
     *
     * @param resp
     */
    @Override
    public void updateScheduleSuccess(Resp resp) {
        Toast.makeText(context, resp.getMessage(), Toast.LENGTH_SHORT).show();
        reLoadScheduleList();
    }

    /**
     * 修改待办失败
     *
     * @param resp
     */
    @Override
    public void updateScheduleError(Resp resp) {
        Toast.makeText(context, resp.getMessage(), Toast.LENGTH_SHORT).show();
    }

    @Override
    public void deleteSuccess(Resp resp) {
        reLoadScheduleList();
        Toast.makeText(context, resp.getMessage(), Toast.LENGTH_SHORT).show();
    }

    @Override
    public void deleteError(Resp resp) {
        Toast.makeText(context, resp.getMessage(), Toast.LENGTH_SHORT).show();
    }
}
